import { ref, computed } from 'vue';
import type { App } from 'vue';

const timeAgo = function (time?: string) {
  if (!time) return '刚刚';

  const now = ref(new Date());
  const diff = computed(() => {
    const timestamp = new Date(time).getTime();
    const nowTimestamp = now.value.getTime();
    const seconds = Math.floor((nowTimestamp - timestamp) / 1000);
    if (seconds < 60) {
      return '刚刚';
    } else if (seconds < 60 * 60) {
      return `${Math.floor(seconds / 60)}分钟前`;
    } else if (seconds < 60 * 60 * 24) {
      return `${Math.floor(seconds / (60 * 60))}小时前`;
    } else if (seconds < 60 * 60 * 24 * 30) {
      return `${Math.floor(seconds / (60 * 60 * 24))}天前`;
    } else if (seconds < 60 * 60 * 24 * 30 * 12) {
      return `${Math.floor(seconds / (60 * 60 * 24 * 30))}月前`;
    } else {
      return `${Math.floor(seconds / (60 * 60 * 24 * 30 * 12))}年前`;
    }
  });

  // 容易有性能问题
  // setInterval(() => {
  // now.value = new Date();
  // }, 1000);

  return diff.value.toString();
};

const useTimeAgo = {
  install(app: App) {
    app.config.globalProperties.$timeAgo = timeAgo;
  },
};

export default useTimeAgo;
